package personal.wang.message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @className: MessageDecoder
 * @Description:
 * @Author: wangyifei
 * @Date: 2024/6/4 11:12
 */
public class MessageDecoder extends ByteToMessageDecoder {
    private static Logger logger = LoggerFactory.getLogger(MessageDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int version = in.readInt();
        int length = in.readInt();
        int contentLength = in.readInt();
        int flag = in.readInt();
        byte[] sessionByte = new byte[length];
        logger.debug("sessionByte length : {}" , length);
        in.readBytes(sessionByte);
        String sessionId = new String(sessionByte , StandardCharsets.UTF_8);
        Header header = new Header(version, length , contentLength , sessionId , flag);
        logger.debug("contentLength:{}" , contentLength);
        byte[] contentByte = new byte[contentLength];
        in.readBytes(contentByte);
        Message message = new Message(header, contentByte);
        out.add(message);
    }
}
// sessiongId='9379f11f-b139-4d12-a52d-e6141028d9a'
// sessiongId='9379f11f-b139-4d12-a52d-e6141028d9a0'